//
//  WechatPayManager.m
//  Paoword
//
//  Created by Wensj on 7/1/16.
//  Copyright © 2016 New. All rights reserved.
//

#import "WechatPayManager.h"
#import "NSDictionary+JsonString2Dic.h"
#import "WXApiObject.h"
#import "WXApiManager.h"

@interface WechatPayManager()

//@property (nonatomic, strong) Response *response;
//@property (nonatomic, strong) MemberProduct *product;

@end

@implementation WechatPayManager

- (instancetype)init {
    if (self = [super init]) {
        [WXApiManager sharedManager].delegate = self;
    }
    return self;
}

+(instancetype)sharedManager {
    static dispatch_once_t onceToken;
    static WechatPayManager *instance;
    dispatch_once(&onceToken, ^{
        instance = [[WechatPayManager alloc] init];
    });
    return instance;
}

- (void)payWithProduct:(NSString *)produce completionBlock:(PaymentCompletionBlock)completionBlock {
    
    if ([WXApi isWXAppInstalled]) {
        NSDictionary *proInfo = [NSDictionary dictionaryWithJsonString:produce];
        
        PayReq *req = [[PayReq alloc] init];
        req.openID = (proInfo[@"appid"] && !([proInfo[@"appid"] isKindOfClass:[NSNull class]])) ? proInfo[@"appid"] : @"";
        req.partnerId = (proInfo[@"partnerid"] && !([proInfo[@"partnerid"] isKindOfClass:[NSNull class]])) ? proInfo[@"partnerid"] : @"";
        req.prepayId = (proInfo[@"prepayid"] && !([proInfo[@"prepayid"] isKindOfClass:[NSNull class]])) ? proInfo[@"prepayid"] : 0;
        req.package = (proInfo[@"package"] && !([proInfo[@"package"] isKindOfClass:[NSNull class]])) ? proInfo[@"package"] : @"";
        req.nonceStr = (proInfo[@"noncestr"] && !([proInfo[@"noncestr"] isKindOfClass:[NSNull class]])) ? proInfo[@"noncestr"] : @"";
        req.timeStamp = (proInfo[@"timestamp"] && !([proInfo[@"timestamp"] isKindOfClass:[NSNull class]])) ? [proInfo[@"timestamp"] intValue] : 0;
        req.sign = (proInfo[@"sign"] && !([proInfo[@"sign"] isKindOfClass:[NSNull class]])) ? proInfo[@"sign"] : @"";
        DLog(@"微信下单结果 : %@", proInfo);
        if (req.prepayId == 0) {
            //@"微信下单失败"
//            PaymentCompletion *completion = [PaymentCompletion initWithPaymentType:PaymentCompletionTypeFailedToOrder message:@"微信下单失败"];
//            CallBlock(weakSelf.paymentCompletionBlock, completion);
        } else {
            BOOL result = [WXApi sendReq:req];
            DLog(@"微信支付调用 : %u %@",result, proInfo);
        }

    }else {
        //@"您还没安装微信客户端"
        
    }
   
}

#pragma mark - WXApiManagerDelegate
- (void)managerDidRecvPayResponse:(PayResp *)resp {
    MMGWeakSelf(weakSelf);
//    if (self.response) {
//        NSDictionary *params = @{@"out_trade_no" : self.response.data[@"trade_no"]};
//        [[PWNetAPIManager sharedManager] requestCheckAlipayOrderState:params andBlock:^(Response *response) {
//            weakSelf.response = nil;
//        }];
//    }
//    
    switch (resp.errCode) {
        case WXSuccess: {
            DLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
            //传递支付结果到CDOVA
//            PaymentCompletion *completion = [PaymentCompletion initWithPaymentType:PaymentCompletionTypeSuccess message:@"支付成功"];
//            CallBlock(self.paymentCompletionBlock, completion);
        }
            break;
        case WXErrCodeCommon: {
//            DLog(@"支付:retcode = %d, restr = %@",resp.errCode, resp.errStr);
//            PaymentCompletion *completion = [PaymentCompletion initWithPaymentType:PaymentCompletionTypeFailed message:@"支付失败"];
//            CallBlock(self.paymentCompletionBlock, completion);
//            
//            // 日志
//            [[Log statisticsLogModelWithPageName:PWLogPageVip actionType:PWLogActionTypeVipBuyFail actionParams:PWLogActionParamWechat, self.product.productId, PWLofActionPayFailTransferFail, nil] save];
        }
            break;
        case WXErrCodeSentFail: {
            DLog(@"支付:retcode = %d, restr = %@",resp.errCode, resp.errStr);
//            PaymentCompletion *completion = [PaymentCompletion initWithPaymentType:PaymentCompletionTypeFailed message:@"支付发送失败"];
//            CallBlock(self.paymentCompletionBlock, completion);
//            
//            // 日志
//            [[Log statisticsLogModelWithPageName:PWLogPageVip actionType:PWLogActionTypeVipBuyFail actionParams:PWLogActionParamWechat, self.product.productId, PWLofActionPayFailSendFail, nil] save];
        }
            break;
        case WXErrCodeAuthDeny: {
            DLog(@"支付:retcode = %d, restr = %@",resp.errCode, resp.errStr);
//            PaymentCompletion *completion = [PaymentCompletion initWithPaymentType:PaymentCompletionTypeFailed message:@"支付授权失败"];
//            CallBlock(self.paymentCompletionBlock, completion);
//            
//            // 日志
//            [[Log statisticsLogModelWithPageName:PWLogPageVip actionType:PWLogActionTypeVipBuyFail actionParams:PWLogActionParamWechat, self.product.productId, PWLofActionPayFailWarrantFail, nil] save];
        }
            break;
        case WXErrCodeUnsupport: {
            DLog(@"支付:retcode = %d, restr = %@",resp.errCode, resp.errStr);
//            PaymentCompletion *completion = [PaymentCompletion initWithPaymentType:PaymentCompletionTypeFailed message:@"您的微信版本不支持微信支付功能"];
//            CallBlock(self.paymentCompletionBlock, completion);
//            
//            // 日志
//            [[Log statisticsLogModelWithPageName:PWLogPageVip actionType:PWLogActionTypeVipBuyFail actionParams:PWLogActionParamWechat, self.product.productId, PWLofActionPayFailOther, nil] save];
        }
            break;
        case WXErrCodeUserCancel: {
            DLog(@"支付:retcode = %d, restr = %@",resp.errCode, resp.errStr);
//            PaymentCompletion *completion = [PaymentCompletion initWithPaymentType:PaymentCompletionTypeCancel message:@"支付取消"];
//            CallBlock(self.paymentCompletionBlock, completion);
//            
//            // 日志
//            [[Log statisticsLogModelWithPageName:PWLogPageVip actionType:PWLogActionTypeVipBuyFail actionParams:PWLogActionParamWechat, self.product.productId, PWLofActionPayFailUserCancelled, nil] save];
        }
            break;
        default: {
            DLog(@"错误，retcode = %d, retstr = %@", resp.errCode,resp.errStr);
//            PaymentCompletion *completion = [PaymentCompletion initWithPaymentType:PaymentCompletionTypeFailed message:@"支付失败"];
//            CallBlock(self.paymentCompletionBlock, completion);
//            
//            // 日志
//            [[Log statisticsLogModelWithPageName:PWLogPageVip actionType:PWLogActionTypeVipBuyFail actionParams:PWLogActionParamWechat, self.product.productId, PWLofActionPayFailPayFail, nil] save];
        }
            break;
    }
}

@end
